package com.hbzhit.common.json;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JacksonStdImpl;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.hbzhit.common.utils.SpringContextUtils;

import java.io.IOException;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;

/**
 * Created with IntelliJ IDEA.
 *
 * @author DING
 * @version 1.0
 * @date 2021/6/23 12:45
 */
@JacksonStdImpl
public class BigDecimalToStringSerializer extends ToStringSerializer {
    public final static BigDecimalToStringSerializer instance = new BigDecimalToStringSerializer();
    
    private String format;

    public String getFormat() {
        return format;
    }

    public void setFormat(String format) {
        this.format = format;
    }

    public BigDecimalToStringSerializer() {
        super(Object.class);
    }

    public BigDecimalToStringSerializer(Class<?> handledType) {
        super(handledType);
    }

    @Override
    public boolean isEmpty(SerializerProvider prov, Object value) {
        if (value == null) {
            return true;
        }
        String str = ((BigDecimal) value).stripTrailingZeros().toPlainString();
        return str.isEmpty();
    }

    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        if (this.format == null) {
            this.format = ((BigDecimalFormatProperties)SpringContextUtils.getBean("bigDecimalFormatProperties")).getFormat();
        }
        DecimalFormat df = new DecimalFormat(this.format);
        df.setRoundingMode(RoundingMode.HALF_UP);
        gen.writeString(df.format(value));
    }

    @Override
    public JsonNode getSchema(SerializerProvider provider, Type typeHint) throws JsonMappingException {
        return createSchemaNode("string", true);
    }

    @Override
    public void serializeWithType(Object value, JsonGenerator gen,
                                  SerializerProvider provider, TypeSerializer typeSer)
            throws IOException {
        // no type info, just regular serialization
        serialize(value, gen, provider);
    }
}
